<?php

declare(strict_types=1);

namespace App\Common\Service;

class LinkFilterService
{
    protected array $whitelist;

    public function __construct(array $whitelist)
    {
        // 转换为小写确保比较一致
        $this->whitelist = array_map('strtolower', $whitelist);
    }

    public function filter(string $content): string
    {
        // 匹配所有HTTP/HTTPS链接
        $pattern = '/\bhttps?:\/\/\S+/i';
        return preg_replace_callback($pattern, function ($matches) {
            $url = $matches[0];
            $host = parse_url($url, PHP_URL_HOST);

            if ($host === null) {
                return $url; // 保留无法解析的URL
            }

            $host = strtolower($host);
            if (!in_array($host, $this->whitelist)) {
                return ''; // 替换为非白名单链接为空
            }
            return $url;
        }, $content);
    }
}